package starlingui.manager
{
	import com.imcrl.core.imcrl_internal;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	
	import starling.events.Event;
	import starling.events.EventDispatcher;
	import starling.textures.Texture;
	
	import starlingui.component.event.ProgressEvent;
	
	public class TextureLoader extends EventDispatcher
	{
		protected var _isReady:Boolean=false;
		private var _texture:Texture;
		private var _content:BitmapData;
		public function TextureLoader()
		{
			super();
		}
		
		public function load(url:String):void{
			var loader:Loader=new Loader();
			var loadInfo:LoaderInfo=loader.contentLoaderInfo;
			loadInfo.addEventListener(flash.events.Event.COMPLETE,complete);
			loadInfo.addEventListener(flash.events.ProgressEvent.PROGRESS,progress);
			loadInfo.addEventListener(flash.events.IOErrorEvent.IO_ERROR,complete);
			loadInfo.addEventListener(flash.events.SecurityErrorEvent.SECURITY_ERROR,complete);
			loader.load(new URLRequest(url))
		}
		
		/**
		 * 进度只存一份; 
		 */		
		private var e:starlingui.component.event.ProgressEvent=new starlingui.component.event.ProgressEvent(starlingui.component.event.ProgressEvent.PROGRESS,0,0);
		private function progress(event:flash.events.ProgressEvent):void{
			if(this.hasEventListener(event.type)){
				e.imcrl_internal::_bytesLoaded=event.bytesLoaded;
				e.imcrl_internal::_bytesTotal=event.bytesTotal;
				this.dispatchEvent(e);
			}
		}
		
		
		public function complete(e:flash.events.Event):void{
			var loadInfo:LoaderInfo=e.target as LoaderInfo;
			loadInfo.removeEventListener(flash.events.Event.COMPLETE,complete);
			loadInfo.removeEventListener(flash.events.ProgressEvent.PROGRESS,progress);
			loadInfo.removeEventListener(flash.events.IOErrorEvent.IO_ERROR,complete);
			loadInfo.removeEventListener(flash.events.SecurityErrorEvent.SECURITY_ERROR,complete);
			
			if(e.type !=flash.events.Event.COMPLETE){
				trace(e);
				return;
			}
			_isReady=true;
			
			_content=(loadInfo.content as Bitmap).bitmapData;
			
			if(hasEventListener(e.type)){
				var event:starling.events.Event=new starling.events.Event(e.type);
				this.dispatchEvent(event);
			}
		}
		public function get isReady():Boolean{
			return _isReady;
		}
		
		
		public function get texture():Texture{
			if(_isReady && _texture==null){
				_texture=Texture.fromBitmapData(_content,false);
			}
			return _texture
		}
		
		public function get content():BitmapData{
			return _content;
		}
		
	}
}